package com.dyb.recuitment.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.dyb.recuitment.common.Result;
import io.swagger.annotations.Api;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@RestController
@Api(tags = "图片显示(Picture)")
@RequestMapping("/picture")
public class PictureController {

    @ResponseBody
    @GetMapping(value = "/show", produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] picture(String filename) {
        try {
            File file = new File("D:\\JavaProject\\proj\\recruitment\\src\\main\\resources\\static\\images\\"+filename);
            FileInputStream inputStream = new FileInputStream(file);
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return bytes;
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping(value = "/uploadfile")
    public Object uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        // 文件名
        String fileName = file.getOriginalFilename();
        // 在file文件夹中创建名为fileName的文件
        assert fileName != null;
        int split = fileName.lastIndexOf(".");
        // 文件后缀，用于判断上传的文件是否是合法的
        String suffix = fileName.substring(split+1,fileName.length());
        //判断文件类型，因为我这边是图片，所以只设置三种合法格式
        String url = "";
        if("jpg".equals(suffix) || "jpeg".equals(suffix) || "png".equals(suffix)) {
            // 正确的类型，保存文件
            try {
                File path = new File(ResourceUtils.getURL("classpath:").getPath());
                File upload = new File(path.getAbsolutePath(), "upload/");
                if(!upload.exists()) {
                    upload.mkdirs();
                }
                String newName = System.currentTimeMillis() + "."+suffix;
                String homepath = "/home/upload/images";
                File savedFile = new File(upload + "/" + newName);
                file.transferTo(savedFile);
                url = savedFile.getAbsolutePath();
                System.out.println("图片上传完毕，存储地址为："+ url);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }else {
            //错误的类型，返回错误提示

        }
        File savedFile;
        return Result.success(url, "上传成功!");
    }
}
